﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace MiniBottles.Models
{

  
    public class DataContext : DbContext
    {
        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<DictCollection> DictCollection { get; set; }
        public DbSet<DictCategory> DictCategory { get; set; }
        public DbSet<Bottle> Bottles { get; set; }
        public DbSet<Gallery> Galleries { get; set; }
        public DbSet<GuestBook> GuestBooks { get; set; }
        public DbSet<Visitor> Visitors { get; set; }

        public DataContext()
            : base("DefaultConnection")
        {
                    
        }

        public override int SaveChanges()
        {

            try
            {
                ObjectContext context = ((IObjectContextAdapter)this).ObjectContext;

                var vs = from e in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                         where
                             e.IsRelationship == false &&
                             e.Entity != null &&
                             typeof(Base).IsAssignableFrom(e.Entity.GetType())
                         select e;

                foreach (var entry in vs)
                {
                    Base entityBase = entry.Entity as Base;

                    if (entry.State == EntityState.Added)
                    {
                        entityBase.CreateDate = DateTime.Now;
                    }

                    entityBase.UpdateDate = DateTime.Now;
                }

                return base.SaveChanges();
          }
          catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            return 0;
        }
      

        
    }
}